package com.cyf.filmDownload.m3u8.listener;

import com.cyf.filmDownload.common.threadPool.ThreadPoolConfig;
import com.cyf.filmDownload.config.AppConfig;
import com.cyf.filmDownload.m3u8.entity.DownloadProgress;
import com.cyf.filmDownload.m3u8.task.ComposeTask;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Data
public class DownloadListener extends Thread {

    private ConcurrentHashMap<String, DownloadProgress> downloadProgressMap = new ConcurrentHashMap<>();

    @Override
    public void run() {
        log.info("下载进度监听线程启动");
        while (true) {
            try {
                Thread.sleep(AppConfig.listeningInterval);
                if (downloadProgressMap.isEmpty()) {
                    continue;
                }
                Iterator<Map.Entry<String, DownloadProgress>> iterator = downloadProgressMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, DownloadProgress> entry = iterator.next();
                    String video = entry.getKey();
                    DownloadProgress progress = entry.getValue();
                    if (progress.isFinish()) {
                        iterator.remove();
                        log.info("{}下载完成，开始合并", video);
                        ThreadPoolConfig.composeThreadPool.execute(new ComposeTask(progress.getParserResult()));
                    } else {
                        log.info("{}下载进度：{}", video, progress.getProgress());
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("下载进度监听线程异常", e);
            }
        }
    }

    public void addDownloadProgress(String key, DownloadProgress downloadProgress) {
        downloadProgressMap.put(key, downloadProgress);
    }
}